<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>重置密码</span>
    </div>
    <!-- 表单 -->
    <el-form :model="pwdForm" :rules="pwdFormRules" ref="pwdFormRef" label-width="100px">

      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password"></el-input>
      </el-form-item>

      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password"></el-input>
      </el-form-item>

      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="updatePwdFn">修改密码</el-button>
        <el-button @click="resetFn">重置</el-button>
      </el-form-item>

    </el-form>
  </el-card>
</template>

<script>
import { updatePwdAPI } from '@/api/index' // 修改密码的接口
export default {
  name: 'UserPwd',
  data () {
    const samePwd = (rule, value, callback) => {
      // 新密码和原密码不能一样
      if (value === this.pwdForm.old_pwd) {
        callback(new Error('新密码和原密码不能一致'))
      } else { // 不一致就通过
        callback()
      }
    }
    const rePwd = (rule, value, callback) => {
      // 验证两次输入的密码是否一致
      if (value === this.pwdForm.new_pwd) {
        callback()
      } else {
        callback(new Error('两次输入的密码不一致'))
      }
    }

    return {
      // 表单的数据对象
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      // 表单的验证规则对象
      pwdFormRules: {
        old_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' }

        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' },
          // 自定义规则
          { validator: samePwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请再次确认新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' },
          // 自定义规则
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    resetFn () { // 重置
      // this.pwdForm = {}
      this.$refs.pwdFormRef.resetFields()
    },
    updatePwdFn () { // 点击修改密码请求后台
      this.$refs.pwdFormRef.validate(async valid => { // 兜底校验
        if (valid) { // 通过
          const { data } = await updatePwdAPI(this.pwdForm)
          if (data.code === 0) {
            this.$message.success('修改密码成功 请重新登录')
            // 成功之后强制退出到登录页面
            this.$router.push('login')
          } else {
            this.$message.error(data.message)
          }
        } else { // 未通过校验则退出
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
